<template>
    <div class="app">
        <header class="header">
            <div class="header-content">
                <div class="logo-section">
                    <div class="logo">📊</div>
                    <div class="title-group">
                        <h1>开料计算器</h1>
                        <p class="subtitle">Professional Cutting Optimizer</p>
                    </div>
                </div>
            </div>
        </header>

        <div class="main-container">
            <div class="calculator">
                <div class="left-panel">
                    <div class="input-section">
                        <div class="input-card">
                            <div class="card-header">
                                <span class="icon">📏</span>
                                <h3>目标尺寸</h3>
                            </div>
                            <div class="size-inputs">
                                <div class="input-group">
                                    <div class="input-field">
                                        <label>宽度</label>
                                        <div class="input-wrapper">
                                            <input type="number" v-model="baseSize.width" placeholder="请输入宽度" />
                                            <span class="unit">mm</span>
                                        </div>
                                    </div>
                                    <div class="input-field">
                                        <label>高度</label>
                                        <div class="input-wrapper">
                                            <input type="number" v-model="baseSize.height" placeholder="请输入高度" />
                                            <span class="unit">mm</span>
                                        </div>
                                    </div>
                                </div>


                            </div>
                            <div class="input-field">
                                <!-- Shape Selection -->
                                <label>形状：</label>
                                <select v-model="shape">
                                    <option value="rectangular">直角</option>
                                    <option value="rounded">圆角</option>
                                </select>
                            </div>

                            <div class="input-field">
                                <!-- 订单数量输入框 -->
                                <label for="orderQuantity">订单数量：</label>
                                <input v-model.number="orderQuantity" type="number" id="orderQuantity" min="1" />
                            </div>
                        </div>


                        <div class="input-card">
                            <div class="card-header">
                                <span class="icon">📐</span>
                                <h3>自定义板材</h3>
                            </div>
                            <div class="size-inputs">
                                <div class="input-group">
                                    <div class="input-field">
                                        <label>宽度</label>
                                        <div class="input-wrapper">
                                            <input type="number" v-model="customMaterial.width" placeholder="请输入宽度" />
                                            <span class="unit">mm</span>
                                        </div>
                                    </div>
                                    <div class="input-field">
                                        <label>高度</label>
                                        <div class="input-wrapper">
                                            <input type="number" v-model="customMaterial.height" placeholder="请输入高度" />
                                            <span class="unit">mm</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="input-card materials-card">
                            <div class="card-header">
                                <span class="icon">📋</span>
                                <h3>标准板材</h3>
                            </div>
                            <div class="material-categories">
                                <div v-for="(category, categoryKey) in materialCategories" 
                                     :key="categoryKey" 
                                     class="material-category">
                                    <div class="category-header" @click="toggleCategory(categoryKey)">
                                        <div class="category-title">
                                            <div class="checkbox-wrapper category-checkbox">
                                                <input type="checkbox" 
                                                       :checked="isCategoryFullySelected(categoryKey)"
                                                       @click.stop="toggleCategorySelection(categoryKey)" />
                                                <span class="checkmark"></span>
                                            </div>
                                            <h4>{{ category.name }}</h4>
                                        </div>
                                        <span class="expand-icon" :class="{ 'expanded': expandedCategories[categoryKey] }">
                                            ▼
                                        </span>
                                    </div>
                                    <div class="material-options" v-show="expandedCategories[categoryKey]">
                                        <label v-for="(size, index) in category.sizes" 
                                               :key="`${categoryKey}-${index}`" 
                                               class="material-option">
                                            <div class="checkbox-wrapper">
                                                <input type="checkbox" 
                                                       :value="size" 
                                                       v-model="selectedMaterials"
                                                       :checked="isSelected(size)" />
                                                <span class="checkmark"></span>
                                            </div>
                                            <span class="checkbox-label">{{ size }}</span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="button-group">
                            <button class="calculate-btn" 
                                ref="calculateBtn"
                                @click="calculate" 
                                tabindex="0">
                                <span class="btn-icon">🔄</span>
                                生成方案
                            </button>
                            <button class="reset-btn" @click="clearStoredData">
                                <span class="btn-icon">🗑️</span>
                                重置数据
                            </button>
                        </div>
                    </div>
                </div>

                <div class="right-panel" v-if="showResults">
                    <div class="results-section">
                        <div class="results-card">
                            <div class="card-header">
                                <span class="icon">📊</span>
                                <h3>最优方案评估有3个维度：利用率最高、订单张数最少、涂刷方数最低</h3>
                            </div>
                            <div class="table-container">
                                <table>
                                    <thead>
                                        <tr>
                                            <th>开料尺寸</th>
                                            <th>原料尺寸</th>
                                            <th>方向</th>
                                            <th>开数(横×纵=总数)</th>
                                            <th>剩余(宽/高)</th>
                                            <th>利用率</th>
                                            <th>订单数量(张数)</th>
                                            <th>涂刷方数</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="(result, index) in results" :key="index"
                                            :class="{ 'selected': selectedResult === index }"
                                            @click="selectResult(index)">
                                            <td>{{ result.targetSize }}</td>
                                            <td>{{ result.originalSize }}</td>
                                            <td>
                                                <span
                                                    :class="['direction-tag', result.direction === '顺向' ? 'horizontal' : 'vertical']">
                                                    {{ result.direction }}
                                                </span>
                                            </td>
                                            <td>{{ formatCuts(result.cuts) }}</td>
                                            <td :class="{ 'warning': result.isWarning }">{{ result.remaining }}</td>
                                            <td :class="{ 'good': result.efficiency >= 80 }">{{ result.efficiency }}%
                                            </td>
                                            <td>{{ result.orderQuantity }}</td>
                                            <td>{{ result.paintSquares }}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <div v-if="selectedResult !== null" class="diagram-card">
                            <div class="card-header">
                                <span class="icon">🎯</span>
                                <h3>切割示意图</h3>
                            </div>
                            <CuttingDiagram 
                                :material="getMaterialSize(results[selectedResult].originalSize)"
                                :target="getMaterialSize(results[selectedResult].targetSize)"
                                :cuts="getCuts(results[selectedResult].cuts)"
                                :is-horizontal="results[selectedResult].direction === '顺向'"
                                :selected-blocks="selectedBlocks"
                                @block-select="handleBlockSelect"
                                @update:cuts="handleCutsUpdate"
                            />
                            
                            
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch, onUnmounted } from 'vue';
import CuttingDiagram from '../components/CuttingDiagram.vue';
import { useRouter } from 'vue-router';

// 1. 首先定义材料分类的类型
interface MaterialCategory {
    name: string;
    sizes: string[];
}

type MaterialCategories = {
    tearProof: MaterialCategory;
    regular: MaterialCategory;
    pvc: MaterialCategory;
}

// 2. 定义 materialCategories 时指定类型
const materialCategories: MaterialCategories = {
    tearProof: {
        name: '撕不烂纸',
        sizes: [
            '787 x 1090mm',
            '787 x 545mm',
            '787 x 363mm',
            '393 x 545mm',
            '889 x 1090mm',
            '889 x 545mm',
            '889 x 363mm',
            '444 x 545mm'
        ]
    },
    regular: {
        name: '常规用纸',
        sizes: [
            '787 x 1090mm',
            '787 x 545mm',
            '787 x 363mm',
            '393 x 545mm',
            '889 x 1194mm',
            '889 x 597mm',
            '889 x 398mm',
            '444 x 597mm'
        ]
    },
    pvc: {
        name: 'PVC发泡板/胶片',
        sizes: [
            '1220 x 1220mm',
            '1220 x 813mm',
            '1220 x 610mm',
            '813 x 610mm',
            '610 x 610mm'
        ]
    }
};

// 1. 首先声明接口和类型
interface Material {
    width: number;
    height: number;
}

interface CutResult {
    targetSize: string;
    originalSize: string;
    direction: string;
    cuts: string;
    remaining: string;
    isWarning: boolean;
    efficiency: number;
    orderQuantity: any;
    paintSquares: number;
}

type Shape = 'rectangular' | 'rounded';

// 2. 然后声明响应式变量
const orderQuantity = ref<any>(200)
const baseSize = ref<Material>({ width: 0, height: 0 });
const customMaterial = ref<Material>({ width: 0, height: 0 });
const shape = ref<Shape>('rectangular')
const selectedMaterials = ref<string[]>([
    '787 x 1090mm',
    '787 x 545mm',
    '889 x 1090mm',
    '889 x 545mm'
]);
const showResults = ref(true);
const results = ref<CutResult[]>([]);
const selectedResult = ref<number | null>(null);
const calculateBtn = ref<HTMLButtonElement | null>(null);
const selectedBlocks = ref<{row: number; col: number}[]>([]);

// 3. 定义存储相关的常量和函数
const STORAGE_KEYS = {
    BASE_SIZE: 'cutting-calculator-base-size',
    CUSTOM_MATERIAL: 'cutting-calculator-custom-material',
    SHAPE: 'cutting-calculator-shape',
    ORDER_QUANTITY: 'cutting-calculator-order-quantity',
    SELECTED_MATERIALS: 'cutting-calculator-selected-materials'
};

const loadStoredData = () => {
    try {
        const storedBaseSize = localStorage.getItem(STORAGE_KEYS.BASE_SIZE);
        const storedCustomMaterial = localStorage.getItem(STORAGE_KEYS.CUSTOM_MATERIAL);
        const storedShape = localStorage.getItem(STORAGE_KEYS.SHAPE);
        const storedOrderQuantity = localStorage.getItem(STORAGE_KEYS.ORDER_QUANTITY);
        const storedSelectedMaterials = localStorage.getItem(STORAGE_KEYS.SELECTED_MATERIALS);

        if (storedBaseSize) {
            baseSize.value = JSON.parse(storedBaseSize);
        }
        if (storedCustomMaterial) {
            customMaterial.value = JSON.parse(storedCustomMaterial);
        }
        if (storedShape) {
            shape.value = storedShape as Shape;
        }
        if (storedOrderQuantity) {
            orderQuantity.value = JSON.parse(storedOrderQuantity);
        }
        if (storedSelectedMaterials) {
            selectedMaterials.value = JSON.parse(storedSelectedMaterials);
        }
    } catch (error) {
        console.error('Error loading stored data:', error);
    }
};

const clearStoredData = () => {
    Object.values(STORAGE_KEYS).forEach(key => {
        localStorage.removeItem(key);
    });
    // 重置所有值到默认状态
    baseSize.value = { width: 0, height: 0 };
    customMaterial.value = { width: 0, height: 0 };
    shape.value = 'rectangular';
    orderQuantity.value = 200;
    selectedMaterials.value = [
        '787 x 1090mm',
        '787 x 545mm',
        '889 x 1090mm',
        '889 x 545mm'
    ];
};

// 4. 设置 watch
watch(
    () => baseSize.value,
    (newVal) => {
        localStorage.setItem(STORAGE_KEYS.BASE_SIZE, JSON.stringify(newVal));
    },
    { deep: true }
);

watch(
    () => customMaterial.value,
    (newVal) => {
        localStorage.setItem(STORAGE_KEYS.CUSTOM_MATERIAL, JSON.stringify(newVal));
    },
    { deep: true }
);

watch(
    () => shape.value,
    (newVal) => {
        localStorage.setItem(STORAGE_KEYS.SHAPE, newVal);
    }
);

watch(
    () => orderQuantity.value,
    (newVal) => {
        localStorage.setItem(STORAGE_KEYS.ORDER_QUANTITY, JSON.stringify(newVal));
    }
);

watch(
    () => selectedMaterials.value,
    (newVal) => {
        localStorage.setItem(STORAGE_KEYS.SELECTED_MATERIALS, JSON.stringify(newVal));
    }
);

// 5. 初始化路由和加载数据
const router = useRouter();

const handleKeyPress = (event: KeyboardEvent) => {
    if (event.key === 'Enter') {
        calculateBtn.value?.click();
    }
};

onMounted(() => {
    const query = router.currentRoute.value.query;
    if (query.ow || query.oh || query.shape || query.quantity) {
        // 如果URL中有参数，优先使用URL参数
        baseSize.value.width = parseInt(query.ow as string) || baseSize.value.width;
        baseSize.value.height = parseInt(query.oh as string) || baseSize.value.height;
        shape.value = (query.shape as Shape) || shape.value;
        orderQuantity.value = parseInt(query.quantity as string) || orderQuantity.value;
    } else {
        // 否则加载本地存储的数据
        loadStoredData();
    }

    // 添加键盘事件监听
    document.addEventListener('keypress', handleKeyPress);
});

onUnmounted(() => {
    document.removeEventListener('keypress', handleKeyPress);
});

const targetSize = computed(() => {
    let size = { ...baseSize.value };
    if (shape.value === 'rounded') {
        size.width += 5;
        size.height += 5;
    }
    return size;
})


const calculate = () => {
    results.value = [];
    const materials = [...selectedMaterials.value];

    if (customMaterial.value.width && customMaterial.value.height) {
        materials.push(`${customMaterial.value.width} x ${customMaterial.value.height}mm`);
    }

    materials.forEach(material => {
        const [width, height] = material.split('x').map(dim => parseInt(dim));
        calculateCuts({ width, height });
    });

    // 按利用率从高到低排序
    results.value.sort((a, b) => b.efficiency - a.efficiency);
    results.value.sort((a, b) => {
        // 使用正则表达式提取括号中的数字
        const quantityA = parseInt(a.orderQuantity.match(/\((\d+)\)/)?.[1] || '0');
        const quantityB = parseInt(b.orderQuantity.match(/\((\d+)\)/)?.[1] || '0');

        // 按照括号内的数字升序排序
        return quantityA - quantityB;
    }
    );
    results.value.sort((a, b) => a.paintSquares - b.paintSquares);


    showResults.value = true;
};

const calculateCuts = (material: Material) => {
    // 计算最大可能的开数
    const maxHorizontalCuts = {
        x: Math.floor(material.width / targetSize.value.width),
        y: Math.floor(material.height / targetSize.value.height)
    };

    const maxVerticalCuts = {
        x: Math.floor(material.width / targetSize.value.height),
        y: Math.floor(material.height / targetSize.value.width)
    };

    // 计算并优化横向开数
    let horizontalCuts = { ...maxHorizontalCuts };
    let horizontalRemaining = {
        width: material.width - (targetSize.value.width * horizontalCuts.x),
        height: material.height - (targetSize.value.height * horizontalCuts.y)
    };

    // 如果剩余宽度小于10mm，减少一列
    if (horizontalRemaining.width > 0 && horizontalRemaining.width < 1) {
        horizontalCuts.x--;
        horizontalRemaining.width = material.width - (targetSize.value.width * horizontalCuts.x);
    }

    // 如果剩余高度小于10mm，减少一行
    if (horizontalRemaining.height > 0 && horizontalRemaining.height < 1) {
        horizontalCuts.y--;
        horizontalRemaining.height = material.height - (targetSize.value.height * horizontalCuts.y);
    }

    // 计算并优化纵向开数
    let verticalCuts = { ...maxVerticalCuts };
    let verticalRemaining = {
        width: material.width - (targetSize.value.height * verticalCuts.x),
        height: material.height - (targetSize.value.width * verticalCuts.y)
    };

    // 如果剩余宽度小于10mm，减少一列
    if (verticalRemaining.width > 0 && verticalRemaining.width < 1) {
        verticalCuts.x--;
        verticalRemaining.width = material.width - (targetSize.value.height * verticalCuts.x);
    }

    // 如果剩余高度小于10mm，减少一行
    if (verticalRemaining.height > 0 && verticalRemaining.height < 1) {
        verticalCuts.y--;
        verticalRemaining.height = material.height - (targetSize.value.width * verticalCuts.y);
    }

    // 计算横向利用率
    const horizontalEfficiency = calculateEfficiency(
        material,
        targetSize.value,
        horizontalCuts
    );

    // 计算纵向利用率
    const verticalEfficiency = calculateEfficiency(
        material,
        { width: targetSize.value.height, height: targetSize.value.width },
        verticalCuts
    );

    // 添加横向结果
    results.value.push({
        targetSize: `${targetSize.value.width}x${targetSize.value.height}`,
        originalSize: `${material.width} x ${material.height}`,
        direction: '顺向',
        cuts: `${horizontalCuts.x}x${horizontalCuts.y}`,
        remaining: `${horizontalRemaining.width}/${horizontalRemaining.height}`,
        isWarning: horizontalRemaining.width < 20 || horizontalRemaining.height < 20,
        efficiency: horizontalEfficiency,
        orderQuantity: `${Math.floor((orderQuantity.value * 1.05) / (horizontalCuts.x * horizontalCuts.y) + 1) * (horizontalCuts.x * horizontalCuts.y)}(${Math.floor((orderQuantity.value * 1.05) / (horizontalCuts.x * horizontalCuts.y) + 1)})`,
        paintSquares: Math.floor((material.width * material.height) * Math.floor((orderQuantity.value * 1.05) / (horizontalCuts.x * horizontalCuts.y) + 1) / 10000) / 100
    });

    // 添加纵向结果
    results.value.push({
        targetSize: `${targetSize.value.width}x${targetSize.value.height}`,
        originalSize: `${material.width} x ${material.height}`,
        direction: '逆向',
        cuts: `${verticalCuts.x}x${verticalCuts.y}`,
        remaining: `${verticalRemaining.width}/${verticalRemaining.height}`,
        isWarning: verticalRemaining.width < 20 || verticalRemaining.height < 20,
        efficiency: verticalEfficiency,
        orderQuantity: `${Math.floor((orderQuantity.value * 1.05) / (verticalCuts.x * verticalCuts.y) + 1) * (verticalCuts.x * verticalCuts.y)}(${Math.floor((orderQuantity.value * 1.05) / (verticalCuts.x * verticalCuts.y) + 1)})`,
        paintSquares: Math.floor((material.width * material.height) * Math.floor((orderQuantity.value * 1.05) / (verticalCuts.x * verticalCuts.y) + 1) / 10000) / 100
    });
};

const calculateEfficiency = (
    material: Material,
    target: Material,
    cuts: { x: number; y: number }
): number => {
    const materialArea = material.width * material.height;
    const usedArea = (target.width * target.height) * (cuts.x * cuts.y);
    const efficiency = (usedArea / materialArea) * 100;
    return Math.round(efficiency * 100) / 100; // 保留两位小数
};

const isSelected = (size: string) => {
    return selectedMaterials.value.includes(size);
};

const selectResult = (index: number) => {
    selectedResult.value = index;
    // 重置选中的方块数据
    selectedBlocks.value = [];
};

const getMaterialSize = (sizeStr: string): { width: number; height: number } => {
    const [width, height] = sizeStr.split('x').map(s => parseInt(s));
    return { width, height };
};

const getCuts = (cutsStr: string) => {
    const [x, y] = cutsStr.split(/[x×]/).map(Number);
    return { x: x || 0, y: y || 0 };
};

const formatCuts = (cuts: string): string => {
    const [x, y] = cuts.split('x').map(Number);
    return `${x}×${y}=${x * y}`;
};

const handleBlockSelect = (position: {row: number; col: number}) => {
    const index = selectedBlocks.value.findIndex(
        block => block.row === position.row && block.col === position.col
    );
    
    if (index === -1) {
        selectedBlocks.value.push(position);
    } else {
        selectedBlocks.value.splice(index, 1);
    }
};

const handleCutsUpdate = (newCuts: { x: number; y: number }) => {
    if (selectedResult.value === null) return;
    
    const result = results.value[selectedResult.value];
    result.cuts = `${newCuts.x}×${newCuts.y}`;
    
    const targetDimensions = getMaterialSize(result.targetSize);
    const materialDimensions = getMaterialSize(result.originalSize);
    
    let widthRemaining: number, heightRemaining: number;
    
    if (result.direction === '顺向') {
        widthRemaining = materialDimensions.width - targetDimensions.width * newCuts.x;
        heightRemaining = materialDimensions.height - targetDimensions.height * newCuts.y;
    } else {
        widthRemaining = materialDimensions.width - targetDimensions.height * newCuts.x;
        heightRemaining = materialDimensions.height - targetDimensions.width * newCuts.y;
    }
    
    result.remaining = `${Math.max(0, widthRemaining)}/${Math.max(0, heightRemaining)}`;
    
    const area = targetDimensions.width * targetDimensions.height * newCuts.x * newCuts.y;
    const totalArea = materialDimensions.width * materialDimensions.height;
    result.efficiency = Number(((area / totalArea) * 100).toFixed(2));
    
    selectedBlocks.value = [];
};

// const selectedBlocksInfo = computed(() => {
//     if (!selectedResult.value || selectedBlocks.value.length === 0) return null;
    
//     const result = results.value[selectedResult.value];
//     const targetDimensions = getMaterialSize(result.targetSize);
//     const isHorizontal = result.direction === '顺向';
    
//     return {
//         count: selectedBlocks.value.length,
//         width: isHorizontal ? targetDimensions.width : targetDimensions.height,
//         height: isHorizontal ? targetDimensions.height : targetDimensions.width,
//         totalArea: selectedBlocks.value.length * targetDimensions.width * targetDimensions.height
//     };
// });

// 添加新的响应式变量来控制折叠状态和全选状态
const expandedCategories = ref<Record<keyof MaterialCategories, boolean>>({
    tearProof: false,
    regular: false,
    pvc: false
});

const categorySelected = ref<Record<keyof MaterialCategories, boolean>>({
    tearProof: true,
    regular: true,
    pvc: true
});

// 添加处理折叠和全选的方法
const toggleCategory = (categoryKey: keyof MaterialCategories) => {
    expandedCategories.value[categoryKey] = !expandedCategories.value[categoryKey];
};

const toggleCategorySelection = (categoryKey: keyof MaterialCategories) => {
    const isSelected = !categorySelected.value[categoryKey];
    categorySelected.value[categoryKey] = isSelected;
    
    const categorySizes = materialCategories[categoryKey].sizes;
    if (isSelected) {
        selectedMaterials.value = [...new Set([
            ...selectedMaterials.value,
            ...categorySizes
        ])];
    } else {
        selectedMaterials.value = selectedMaterials.value.filter(
            size => !categorySizes.includes(size)
        );
    }
};

// 添加计算属性来检查类别是否全选
const isCategoryFullySelected = computed(() => {
    return (categoryKey: keyof MaterialCategories) => {
        const categorySizes = materialCategories[categoryKey].sizes;
        return categorySizes.every((size: string) => selectedMaterials.value.includes(size));
    };
});

// 添加监听器来更新类别选择状态
watch(selectedMaterials, () => {
    (Object.keys(materialCategories) as Array<keyof MaterialCategories>).forEach(categoryKey => {
        categorySelected.value[categoryKey] = isCategoryFullySelected.value(categoryKey);
    });
}, { deep: true });
</script>

<style scoped>
.app {
    min-height: 100vh;
    background-color: #f4f6f8;
}

.header {
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    padding: 1rem 0;
    position: sticky;
    top: 0;
    z-index: 100;
}

.header-content {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 2rem;
}

.logo-section {
    display: flex;
    align-items: center;
    gap: 1rem;
}

.logo {
    font-size: 1.4em;
}

.title-group {
    display: flex;
    flex-direction: column;
}

h1 {
    color: #1e293b;
    margin: 0;
    font-size: 0.9em;
    font-weight: 600;
}

.subtitle {
    color: #64748b;
    margin: 0;
    font-size: 0.6em;
    letter-spacing: 0.5px;
}

.main-container {
    max-width: 1400px;
    margin: 2rem auto;
    padding: 0 2rem;
}

.calculator {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 1rem;
    align-items: start;
}

.input-section {
    display: flex;
    flex-direction: column;
    gap: 0.6rem;
}

.input-card,
.results-card,
.diagram-card {
    background: white;
    border-radius: 6px;
    padding: 0.85rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.7rem;
    padding-bottom: 0.45rem;
    border-bottom: 1px solid #e2e8f0;
}

.card-header h3 {
    color: #1e293b;
    margin: 0;
    font-size: 0.75em;
    font-weight: 600;
}

.input-group {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.input-field {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.input-field label {
    color: #475569;
    font-size: 0.65em;
    font-weight: 500;
}

.input-wrapper {
    position: relative;
}

input[type="number"] {
    width: 100%;
    padding: 0.45rem;
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    font-size: 0.7em;
    transition: all 0.2s;
}

input[type="number"]:focus {
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    outline: none;
}

.unit {
    position: absolute;
    right: 0.5rem;
    top: 50%;
    transform: translateY(-50%);
    color: #64748b;
    font-size: 0.65em;
}

.materials-card {
    max-height: 400px;
    overflow-y: auto;
}

.material-options {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.material-option {
    padding: 0.4rem;
    margin-bottom: 0.2rem;
}

.material-option:last-child {
    margin-bottom: 0;
}

.calculate-btn {
    background-color: #2563eb;
    color: white;
    border: none;
    padding: 0.6rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.7em;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2);
}

.calculate-btn:hover {
    background-color: #1d4ed8;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(37, 99, 235, 0.3);
}

.table-container {
    overflow-x: auto;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
}

table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

th,
td {
    padding: 0.5rem;
    text-align: center;
    font-size: 0.7em;
}

th {
    background-color: #f8fafc;
    color: #1e293b;
    font-weight: 600;
    border-bottom: 2px solid #e2e8f0;
    white-space: nowrap;
}

td {
    border-bottom: 1px solid #e2e8f0;
}

tr:last-child td {
    border-bottom: none;
}

.selected {
    background-color: #e3f2fd !important;
    border-left: 4px solid #1565c0;
    border-right: 4px solid #1565c0;
    position: relative;
    font-weight: 500;
    box-shadow: 0 0 8px rgba(21, 101, 192, 0.1);
}

.selected td {
    background-color: #e3f2fd !important;
    color: #1565c0;
    position: relative;
    z-index: 1;
}

.selected td:first-child {
    padding-left: calc(0.5rem - 4px);
}

.selected td:last-child {
    padding-right: calc(0.5rem - 4px);
}

.selected td.warning {
    color: #dc2626 !important;
}

.selected td.good {
    color: #059669 !important;
}

tr {
    cursor: pointer;
    transition: all 0.2s ease;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    position: relative;
}

tr:hover:not(.selected) {
    background-color: #f3f4f6;
    border-left: 4px solid #e5e7eb;
    border-right: 4px solid #e5e7eb;
}

tr:nth-child(even):not(.selected):not(:hover) {
    background-color: #f8fafc;
}

tr:nth-child(odd):not(.selected):not(:hover) {
    background-color: #ffffff;
}

.direction-tag {
    display: inline-block;
    padding: 0.15rem 0.4rem;
    border-radius: 3px;
    font-size: 0.65em;
    font-weight: 500;
}

.horizontal {
    background-color: #dbeafe;
    color: #1e40af;
}

.vertical {
    background-color: #fef3c7;
    color: #92400e;
}

.good {
    color: #059669;
    font-weight: 600;
}

.warning {
    color: #dc2626;
}

@media (max-width: 1200px) {
    .calculator {
        grid-template-columns: 1fr;
    }

    .input-section {
        max-width: 600px;
        margin: 0 auto;
    }
}

/* 滚动条样式 */
.materials-card::-webkit-scrollbar {
    width: 4px;
}

.materials-card::-webkit-scrollbar-track {
    background: #f1f5f9;
}

.materials-card::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 2px;
}

.materials-card::-webkit-scrollbar-thumb:hover {
    background: #57585a;
}

/* 表格单元格交替背景色 */
tr:nth-child(even):not(.selected) {
    background-color: #fafbfc;
}

.button-group {
    display: flex;
    gap: 0.6rem;
}

.reset-btn {
    background-color: #ef4444;
    color: white;
    border: none;
    padding: 0.6rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.7em;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(239, 68, 68, 0.2);
}

.reset-btn:hover {
    background-color: #dc2626;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(239, 68, 68, 0.3);
}

.selected-blocks-info {
    margin-top: 1rem;
    padding: 1rem;
    background: #f8fafc;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
}

.info-header {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-bottom: 0.5rem;
}

.info-header h4 {
    margin: 0;
    font-size: 0.8em;
    color: #1e293b;
}

.info-content {
    display: grid;
    gap: 0.5rem;
}

.info-content p {
    margin: 0;
    font-size: 0.75em;
    color: #475569;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 0.75rem;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.info-label {
    color: #64748b;
    font-size: 0.75em;
    white-space: nowrap;
}

.info-value {
    font-size: 0.75em;
    color: #1e293b;
    font-weight: 500;
}

.material-categories {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.material-category {
    border: 1px solid #e2e8f0;
    border-radius: 4px;
    overflow: hidden;
}

.category-header {
    background-color: #f8fafc;
    padding: 0.5rem;
    border-bottom: 1px solid #e2e8f0;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    user-select: none;
}

.category-title {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.category-checkbox {
    margin-right: 0.5rem;
}

.expand-icon {
    font-size: 0.7em;
    color: #64748b;
    transition: transform 0.2s ease;
}

.expand-icon.expanded {
    transform: rotate(180deg);
}

.category-header:hover {
    background-color: #f1f5f9;
}

.material-options {
    padding: 0.5rem;
    transition: all 0.3s ease;
}

.checkbox-wrapper {
    display: flex;
    align-items: center;
}

.material-option {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.4rem;
    margin-bottom: 0.2rem;
    transition: background-color 0.2s;
}

.material-option:hover {
    background-color: #f8fafc;
    border-radius: 4px;
}
</style>